package com.mune.gulimall.order.listener;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.mune.gulimall.order.config.AlipayTemplate;
import com.mune.gulimall.order.service.OrderService;
import com.mune.gulimall.order.vo.PayAsyncVo;
import com.mune.gulimall.order.vo.PayVo;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
public class OrderPayedListener {
  @Autowired
  OrderService orderService;
  @Autowired
  AlipayTemplate alipayTemplate;

  @PostMapping("/payed/notify")
  public String payed(PayAsyncVo payVo, HttpServletRequest request) throws AlipayApiException {
    Map<String, String> params = new HashMap<>();
    Map<String, String[]> requestParams = request.getParameterMap();
    for (String name : requestParams.keySet()) {
      String[] values = requestParams.get(name);
      String valueStr = "";
      for (int i = 0; i < values.length; i++) {
        valueStr = ( i == values.length - 1 ) ? valueStr + values[i]
                : valueStr + values[i] + ",";
      }
      params.put(name, valueStr);
    }

    boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipay_public_key(),
            alipayTemplate.getCharset(), alipayTemplate.getSign_type()); //调用SDK验证签名

    if (signVerified) {
      System.out.println("签名验证成功...");
      //去修改订单状态
      String result = orderService.handlePayResult(payVo);
      return result;
    } else {
      System.out.println("签名验证失败...");
      return "error";
    }
  }
}
